using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Collections;
using AjaxControlToolkit;

/// <summary>
/// Summary description for AjaxGridView
/// </summary>
namespace NS_Controls
{
	public class AjaxGridView : BulkEditGridView
	{
		public AjaxGridView()
		{
		}

#region Variables
		protected int m_nInitialPageSize = -10;
		private bool m_bHasDateTimeColumns = false;

		protected LinkButton m_lbPageSize;
		protected LinkButton m_lbFilter;
		protected LinkButton m_lbEdit;
		protected LinkButton m_lbInsert;
		protected TextBox m_txtPageSize;
		protected HtmlInputButton m_ButtonAllPages_PageSize;
		protected HtmlInputButton m_ResetButton_PageSize;
#endregion

#region Properties
		public override object DataSource
		{
			get
			{
				object o = base.DataSource;
				if (o == null)
				{
					if (this.Page.Session[this.ClientID + "_DataSource_DataSet"] == null || this.Page.Session[this.ClientID + "_DataSource_TableIndex"] == null)
						throw new Exception("A expirat sesiunea! Reincarcati pagina.");

					o = ((DataSet)this.Page.Session[this.ClientID + "_DataSource_DataSet"]).Tables[(int)this.Page.Session[this.ClientID + "_DataSource_TableIndex"]].DefaultView;
				}
				return o;
			}
			set
			{
				if (!(value is DataView))
					throw new Exception("Sursa gridului trebuie sa fie un DataView.");

				if (this.UseNrCrt)
				{
					if (!((DataView)value).Table.Columns.Contains("NrCrt"))
					{
						DataColumn dc = new DataColumn("NrCrt", Type.GetType("System.Int32"));
						dc.AutoIncrement = true;
						dc.AllowDBNull = false;
						((DataView)value).Table.Columns.Add(dc);
					}

					((DataView)value).Table.Columns["NrCrt"].ReadOnly = false;
					for (int i = 0; i < ((DataView)value).Table.DefaultView.Count; ++i)
					{
						DataRowState drs = ((DataView)value).Table.DefaultView[i].Row.RowState;
						((DataView)value).Table.DefaultView[i]["NrCrt"] = i + 1;
						if (drs == DataRowState.Unchanged)
							((DataView)value).Table.DefaultView[i].Row.AcceptChanges();
					}
					((DataView)value).Table.Columns["NrCrt"].ReadOnly = true;
				}

				base.DataSource = value;
				this.Page.Session[this.ClientID + "_DataSource_DataSet"] = ((DataView)value).Table.DataSet;
				this.Page.Session[this.ClientID + "_DataSource_TableIndex"] = ((DataView)value).Table.DataSet.Tables.IndexOf(((DataView)value).Table);

				this.RequiresDataBinding = true;
			}
		}

		public override int PageSize
		{
			get { return (int)(this.ViewState["PageSize"] ?? 10); }
			set
			{
				this.ViewState["PageSize"] = value;
				if (m_nInitialPageSize < 0 && value > 0)
					m_nInitialPageSize = value;
				this.RequiresDataBinding = true;
			}
		}

		protected SortDirection SortDir
		{
			get { return (SortDirection)(this.ViewState["SortDir"] ?? SortDirection.Descending); }
			set { this.ViewState["SortDir"] = value; this.RequiresDataBinding = true; }
		}

		protected string SortExp
		{
			get { return (string)(this.ViewState["SortExp"] ?? ""); }
			set { this.ViewState["SortExp"] = value; this.RequiresDataBinding = true; }
		}

		public string TotalColumns
		{
			get { return (string)(this.ViewState["TotalColumns"] ?? ""); }
			set { this.ViewState["TotalColumns"] = value; this.RequiresDataBinding = true; }
		}

		public bool TotalOnAllDecimalColumns
		{
			get { return (bool)(this.ViewState["TotalOnAllDecimalColumns"] ?? false); }
			set { this.ViewState["TotalOnAllDecimalColumns"] = value; this.RequiresDataBinding = true; }
		}

		public override string Caption
		{
			get { return (string)(this.ViewState["Caption"] ?? ""); }
			set { this.ViewState["Caption"] = value; this.RequiresDataBinding = true; }
		}

		public string CaptionForXLS
		{
			get { return (string)(this.ViewState["CaptionForXLS"] ?? ""); }
			set { this.ViewState["CaptionForXLS"] = value; this.RequiresDataBinding = true; }
		}

		public string Mode
		{
			get { return (string)(this.ViewState["Mode"] ?? "HTML"); }
			set { this.ViewState["Mode"] = value; this.RequiresDataBinding = true; }
		}

		public string[] LinkColumn
		{
			get { return (string[])(this.ViewState["LinkColumn"] ?? new string[] { }); }
			set { this.ViewState["LinkColumn"] = value; this.RequiresDataBinding = true; }
		}

		public string[] LinkFormat
		{
			get { return (string[])(this.ViewState["LinkFormat"] ?? new string[] { }); }
			set { this.ViewState["LinkFormat"] = value; this.RequiresDataBinding = true; }
		}

		public string[] LinkFields
		{
			get { return (string[])(this.ViewState["LinkFields"] ?? new string[] { }); }
			set { this.ViewState["LinkFields"] = value; this.RequiresDataBinding = true; }
		}

		public string[] LinkInNewWindow
		{
			get { return (string[])(this.ViewState["LinkInNewWindow"] ?? new string[] { }); }
			set { this.ViewState["LinkInNewWindow"] = value; this.RequiresDataBinding = true; }
		}

		public string[] HiddenColumns
		{
			get { return (string[])(this.ViewState["HiddenColumns"] ?? new string[] { }); }
			set { this.ViewState["HiddenColumns"] = value; this.RequiresDataBinding = true; }
		}

		public string[] NotBindableColumns
		{
			get { return (string[])(this.ViewState["NotBindableColumns"] ?? new string[] { }); }
			set { this.ViewState["NotBindableColumns"] = value; this.RequiresDataBinding = true; }
		}

		public string[] ShortDateColumns
		{
			get { return (string[])(this.ViewState["ShortDateColumns"] ?? new string[] { }); }
			set { this.ViewState["ShortDateColumns"] = value; this.RequiresDataBinding = true; }
		}

		public string[] FourDigitsColumns
		{
			get { return (string[])(this.ViewState["FourDigitsColumns"] ?? new string[] { }); }
			set { this.ViewState["FourDigitsColumns"] = value; this.RequiresDataBinding = true; }
		}

		public string[] PercentColumns
		{
			get { return (string[])(this.ViewState["PercentColumns"] ?? new string[] { }); }
			set { this.ViewState["PercentColumns"] = value; this.RequiresDataBinding = true; }
		}

		public string[] ColumnFormatNames
		{
			get { return (string[])(this.ViewState["ColumnFormatNames"] ?? new string[] { }); }
			set { this.ViewState["ColumnFormatNames"] = value; this.RequiresDataBinding = true; }
		}

		public string[] ColumnFormat
		{
			get { return (string[])(this.ViewState["ColumnFormat"] ?? new string[] { }); }
			set { this.ViewState["ColumnFormat"] = value; this.RequiresDataBinding = true; }
		}

		public string[] TranslateColumns
		{
			get { return (string[])(this.ViewState["TranslateColumns"] ?? new string[] { }); }
			set { this.ViewState["TranslateColumns"] = value; this.RequiresDataBinding = true; }
		}

		public string[][] DropDownColumns
		{
			get { return (string[][])(this.ViewState["DropDownColumns"] ?? new string[][] { new string[] { } }); }
			set { this.ViewState["DropDownColumns"] = value; this.RequiresDataBinding = true; }
		}

		public bool EnableExport
		{
			get { return (bool)(this.ViewState["EnableExport"] ?? true); }
			set { this.ViewState["EnableExport"] = value; this.RequiresDataBinding = true; }
		}

		public bool EnableFilter
		{
			get { return (bool)(this.ViewState["EnableFilter"] ?? true); }
			set { this.ViewState["EnableFilter"] = value; this.RequiresDataBinding = true; }
		}

		public bool ShowEditLink
		{
			get { return (bool)(this.ViewState["ShowEditLink"] ?? true); }
			set { this.ViewState["ShowEditLink"] = value; this.RequiresDataBinding = true; }
		}

		public bool ShowInsertLink
		{
			get { return (bool)(this.ViewState["ShowInsertLink"] ?? true); }
			set { this.ViewState["ShowInsertLink"] = value; this.RequiresDataBinding = true; }
		}

		public bool EnableOtherCriterias
		{
			get { return (bool)(this.ViewState["EnableOtherCriterias"] ?? false); }
			set { this.ViewState["EnableOtherCriterias"] = value; this.RequiresDataBinding = true; }
		}

		public bool UseNrCrt
		{
			get { return (bool)(this.ViewState["UseNrCrt"] ?? true); }
			set { this.ViewState["UseNrCrt"] = value; this.RequiresDataBinding = true; }
		}

		private Hashtable HtFilter
		{
			get { return (Hashtable)(this.ViewState["htFilter"] ?? new Hashtable()); }
			set { this.ViewState["htFilter"] = value; }
		}
#endregion

#region Events
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			this.BackColor = Color.White;
			this.BorderColor = Color.FromName("#E7E7FF");
			this.BorderStyle = BorderStyle.Solid;
			this.BorderWidth = Unit.Pixel(1);
			this.CellPadding = 3;
			this.GridLines = GridLines.Both;

			this.PagerSettings.Mode = PagerButtons.NumericFirstLast;
			this.PagerSettings.FirstPageText = Resources.GridView.FirstPageText;
			this.PagerSettings.LastPageText = Resources.GridView.LastPageText;
			this.PagerSettings.NextPageText = Resources.GridView.NextPageText;
			this.PagerSettings.PreviousPageText = Resources.GridView.PreviousPageText;

			this.RowStyle.CssClass = "RowStyleClass";
			this.AlternatingRowStyle.CssClass = "AlternatingRowStyleClass";
			this.PagerStyle.CssClass = "PagerStyleClass";
			this.PagerStyle.HorizontalAlign = HorizontalAlign.Right;
			this.SelectedRowStyle.CssClass = "SelectedRowStyleClass";
			this.SelectedRowStyle.Font.Bold = true;
			this.HeaderStyle.CssClass = "HeaderStyleClass";
			this.HeaderStyle.Font.Bold = true;
			this.FooterStyle.CssClass = "FooterStyleClass";

			this.AllowSorting = true;
			this.AllowPaging = true;
			this.ShowFooter = true;
			this.AutoGenerateColumns = false;
		}

		protected override void OnPreRender(EventArgs e)
		{
			this.ShowFooter = ((this.TotalColumns != null && this.TotalColumns != "") || this.TotalOnAllDecimalColumns);

			if (this.Mode == "XLS")
			{
				this.AllowSorting = false;
				this.AllowPaging = false;
			}
			else
			{
				this.AllowSorting = true;
				this.AllowPaging = (this.PageSize != -1);
			}

			string strCaption = (this.Mode != "XLS" ? this.Caption : this.CaptionForXLS);
			if (strCaption != "")
				this.Caption = "<font size='+1' style='color: #4A3C8C'>" + strCaption + "</font><br><br>";

			string s = @"
				function OnClick_ResetButton_Filter_Find(p, x)
				{
					if (p.id == null)
						return null;
					if (p.id.indexOf(x) != -1)
						return p;
					for (var i=0; i<p.childNodes.length; ++i)
					{
						var y = OnClick_ResetButton_Filter_Find(p.childNodes[i], x);
						if (y != null)
							return y;
					}
					return null;
				}
				function OnClick_ResetButton_Filter2(tbl)
				{
					for (var i=0; i<tbl.rows.length; ++i)
						for (var j=0; j<tbl.rows[0].cells.length; ++j)
							if (tbl.rows[i].cells.length > j && tbl.rows[i].cells[j].childNodes.length > 0 && tbl.rows[i].cells[j].childNodes[0] != null && tbl.rows[i].cells[j].childNodes[0].tagName == 'INPUT')
								tbl.rows[i].cells[j].childNodes[0].value = '';
				}
				function OnClick_ResetButton_Filter(r)
				{
					var p = $get(r).rows[$get(r).rows.length-1].cells[0];
					var x = OnClick_ResetButton_Filter_Find(p, '_tblFilter');
					OnClick_ResetButton_Filter2(x);
					x = OnClick_ResetButton_Filter_Find(p, '_tblFilter2');
					OnClick_ResetButton_Filter2(x);
					x = OnClick_ResetButton_Filter_Find(p, '_txtAlteCriterii');
					x.value = '';
				}
			";

			ScriptManager.RegisterStartupScript(this, typeof(Page), "ResetButton_Filter", s, true);

			this.Save();
			this.RequiresDataBinding = true;
			AddLinkedStyleSheet(this.Page, "~/Styles/Grid.css");
			base.OnPreRender(e);
		}

		protected override void EnsureDataBound()
		{
			base.EnsureDataBound();

			if (this.RequiresDataBinding)
				this.DataBind();
		}

		protected override void OnPageIndexChanging(GridViewPageEventArgs e)
		{
			this.Save();
			this.PageIndex = e.NewPageIndex;
		}

		protected override void OnSorting(GridViewSortEventArgs e)
		{
			this.Save();

			SortDirection sd = SortDir;
			if (sd == SortDirection.Ascending)
				sd = SortDirection.Descending;
			else
				sd = SortDirection.Ascending;

			string strSortExpression = e.SortExpression;
			if (SortExp != "")
				strSortExpression = SortExp;
			SortExp = e.SortExpression;
			if (strSortExpression != e.SortExpression)
				sd = SortDirection.Ascending;

			SortDir = sd;

			DataView dv = (DataView)this.DataSource;
			dv.Sort = e.SortExpression + " " + (sd == SortDirection.Ascending ? "ASC" : "DESC");
			this.DataSource = dv;
		}

		protected override void OnRowCreated(GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.Pager)
			{
				// Page number
				TableCell tc = new TableCell();
				DataControlField[] fields = this.Fields;
				tc.ColumnSpan = (fields.Length > 0 && fields.Length <= 5 ? fields.Length - 1 : 5);
				tc.HorizontalAlign = HorizontalAlign.Left;
				e.Row.Cells.AddAt(0, tc);

				tc.Text = Resources.GridView.Page + " " + (this.PageIndex + 1).ToString() + " " + Resources.GridView.From2 + " " + this.PageCount.ToString() + ". (" + ((DataView)this.DataSource).Count.ToString() + " " + Resources.GridView.Lines + ")";
			}

			base.OnRowCreated(e);
		}

		protected override void OnRowDataBound(GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				if (this.TranslateColumns != null && this.TranslateColumns.Length != 0)
				{// Translate Columns
					DataControlField[] fields = this.Fields;
					foreach (string s in this.TranslateColumns)
					{
						int n = GetColumnOrdinal(fields, s);
						if (n != -1)
						{
							if (e.Row.Cells[n].Controls[0] is HyperLink)
								((HyperLink)e.Row.Cells[n].Controls[0]).Text = Tools.GetHeaderText(((HyperLink)e.Row.Cells[n].Controls[0]).Text);
							if (e.Row.Cells[n].Controls[0] is Label)
								((Label)e.Row.Cells[n].Controls[0]).Text = Tools.GetHeaderText(((Label)e.Row.Cells[n].Controls[0]).Text);
						}
					}
				}
			}
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				if ((this.TotalColumns != null && this.TotalColumns != "") || this.TotalOnAllDecimalColumns)
				{// Totals
					DataTable dt = ((DataView)this.DataSource).Table;
					e.Row.Cells[0].Text = "<b>Total</b>";
					string[] arTotalColumns;
					if (!this.TotalOnAllDecimalColumns)
						arTotalColumns = this.TotalColumns.Split(new char[] { ',' });
					else
					{
						arTotalColumns = new string[dt.Columns.Count];
						for (int i = 0; i < dt.Columns.Count; ++i)
							if (dt.Columns[i].DataType == Type.GetType("System.Decimal") || dt.Columns[i].DataType == Type.GetType("System.Double") || dt.Columns[i].DataType == Type.GetType("System.Float") || dt.Columns[i].DataType == Type.GetType("System.Single"))
								arTotalColumns[i] = dt.Columns[i].ColumnName;
					}
					DataControlField[] fields = this.Fields;
					foreach (string s in arTotalColumns)
					{
						if (s == null || s == "")
							continue;

						decimal d = 0;
						object o = dt.Compute("SUM ([" + s + "])", dt.DefaultView.RowFilter);
						if (o != System.DBNull.Value)
							d = Convert.ToDecimal(o);

						int n = GetColumnOrdinal(fields, s);
						if (n != -1)
						{
							string strFormat = "";
							if (this.Mode != "XLS")
							{
								strFormat = "N";
								if (dt.Columns[s].DataType == Type.GetType("System.Int32") || dt.Columns[s].DataType == Type.GetType("System.Byte"))
									strFormat = "N0";
							}
							e.Row.Cells[n].Text = "<b>" + d.ToString(this.Mode != "XLS" ? strFormat : "") + "</b>";
							e.Row.Cells[n].HorizontalAlign = HorizontalAlign.Right;
							e.Row.Cells[n].Wrap = false;
						}
					}
				}
			}

			base.OnRowDataBound(e);
		}

		private int GetColumnOrdinal(DataControlField[] fields, string s)
		{
			int n = -1;
			string strDataField = "";
			for (int i = 0; i < fields.Length; ++i)
			{
				DataControlField dcfc = fields[i];
				if (dcfc is CheckBoxField)
					strDataField = ((CheckBoxField)dcfc).DataField;
				else if (dcfc is HyperLinkField)
					strDataField = ((HyperLinkField)dcfc).DataTextField;
				else if (dcfc is TextBoxField)
					strDataField = ((TextBoxField)dcfc).DataField;
				else if (dcfc is DropDownField)
					strDataField = ((DropDownField)dcfc).DataField;

				if (strDataField == s)
				{
					n = i;
					break;
				}
			}
			return n;
		}

		protected override void OnRowUpdating(GridViewUpdateEventArgs e)
		{
			DataView dv = ((DataView)this.DataSource).Table.DefaultView;
			DataRowView drv = dv[e.RowIndex + this.PageIndex * this.PageSize];
			GridViewRow r = this.Rows[e.RowIndex];

			UpdateDataRowView(drv, r);
		}

		protected override void OnRowInserting(GridViewInsertEventArgs e)
		{
			base.OnRowInserting(e);

			DataView dv = ((DataView)this.DataSource).Table.DefaultView;
			DataRowView drv = dv.AddNew();
			GridViewRow r = this.InnerTable.Rows[e.RowIndex] as GridViewRow;

			UpdateDataRowView(drv, r);

			string strFilter = dv.RowFilter;
			dv.RowFilter = "";
			int iLen = dv.Count;
			dv.AddNew();
			dv.Delete(iLen);
			dv.RowFilter = strFilter;
		}

		private void UpdateDataRowView(DataRowView drv, GridViewRow r)
		{
			try
			{
				DataControlField[] fields = this.Fields;
				for (int i = 0; i < fields.Length; ++i)
				{
					DataControlField dcf = fields[i];
					if (dcf is CheckBoxField)
					{
						if (!((CheckBoxField)dcf).ReadOnly)
						{
							string strDataField = ((CheckBoxField)dcf).DataField;
							bool bValue = ((CheckBox)r.Cells[i].Controls[0]).Checked;
							if ((bool)drv[strDataField] != bValue)
								drv[strDataField] = bValue;
						}
					}
					else if (dcf is TextBoxField)
					{
						if (!((TextBoxField)dcf).ReadOnly)
						{
							TextBoxField f = dcf as TextBoxField;
							string strDataField = f.DataField;
							string strValue = ((TextBox)r.Cells[i].Controls[0]).Text;
							if (string.Format(f.DataFormatString, drv[strDataField]) != strValue)
								drv[strDataField] = strValue;
						}
					}
					else if (dcf is DropDownField)
					{
						if (!((DropDownField)dcf).ReadOnly)
						{
							DropDownField f = dcf as DropDownField;
							string strDataField = f.DataField;
							string strValue = ((DropDownList)r.Cells[i].Controls[0]).SelectedValue;
							if (string.Format(f.DataFormatString, drv[strDataField]) != strValue)
								drv[strDataField] = strValue;
						}
					}
				}
			}
			catch (Exception)
			{
				drv.CancelEdit();
				throw;
			}
		}

		protected void OnClick_lbPageSize2(object sender, EventArgs e)
		{
			this.Save();

			int nPageSize = Convert.ToInt32(((TextBox)this.InnerTable.Parent.Controls[2]).Text);

			if (nPageSize != -1)
			{
				if (!this.AllowPaging || this.PageSize != nPageSize)
					this.RequiresDataBinding = true;
				this.AllowPaging = true;
				this.PageSize = nPageSize;
			}
			else
			{
				this.AllowPaging = false;
				this.PageSize = nPageSize;
				this.RequiresDataBinding = true;
			}

			if (m_lbPageSize != null)
				ScriptManager.GetCurrent(this.Page).SetFocus(m_lbPageSize);
		}

		protected void OnClick_lbFilter2(object sender, EventArgs e)
		{
			this.Save();

			Table t = this.InnerTable;
			string strFilter = GetFilter(((Table)t.Rows[t.Rows.Count - 1].Cells[0].Controls[5].Controls[0]).Rows[1]);
			if (((DataView)this.DataSource).RowFilter != strFilter)
			{
				((DataView)this.DataSource).RowFilter = strFilter;
				this.RequiresDataBinding = true;
			}
			if (m_lbFilter != null)
				ScriptManager.GetCurrent(this.Page).SetFocus(m_lbFilter);
		}

		protected void OnClick_lbEdit(object sender, EventArgs e)
		{
			this.Save();

			this.EnableEdit = !this.EnableEdit;
			this.RequiresDataBinding = true;
			if (m_lbEdit != null)
				ScriptManager.GetCurrent(this.Page).SetFocus(m_lbEdit);
		}

		protected void OnClick_lbInsert(object sender, EventArgs e)
		{
			this.Save();

			this.EnableInsert = !this.EnableInsert;
			this.RequiresDataBinding = true;
			if (m_lbInsert != null)
				ScriptManager.GetCurrent(this.Page).SetFocus(m_lbInsert);
		}
#endregion

#region Create controls
		protected override System.Collections.ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
		{
			ArrayList columns = new ArrayList();

			if (this.Columns != null && this.Columns.Count > 0)
			{
				// Controale adaugate manual la colectia Columns
				foreach (DataControlField field2 in this.Columns)
					columns.Add(field2);
			}
			else
			{
				m_bHasDateTimeColumns = false;
				DataTable dt = ((DataView)this.DataSource).Table;
				foreach (DataColumn dc in dt.Columns)
				{
					if (Tools.ArrayIndexOf(this.NotBindableColumns, dc.ColumnName) != -1)
						continue;
					if (Tools.ArrayIndexOf(this.HiddenColumns, dc.ColumnName) != -1)
						continue;

					int x = Tools.ArrayIndexOf(this.LinkColumn, dc.ColumnName);
					string strFormat = (this.EnableEdit ? "F" : "N");
					if (x != -1)
					{
						HyperLinkField f = new HyperLinkField();
						f.DataTextField = dc.ColumnName;
						f.HeaderText = Tools.GetHeaderText(dc.ColumnName);
						f.SortExpression = dc.ColumnName;
						f.DataNavigateUrlFormatString = this.Context.Request.ApplicationPath + "/" + this.LinkFormat[x];
						f.DataNavigateUrlFields = this.LinkFields[x].Split(new char[] { ',' });
						if (this.LinkInNewWindow[x] == "1")
							f.Target = "_blank";
						if (dc.DataType == Type.GetType("System.Int32") || dc.DataType == Type.GetType("System.Decimal") || dc.DataType == Type.GetType("System.Float") || dc.DataType == Type.GetType("System.Double") || dc.DataType == Type.GetType("System.Single") || dc.DataType == Type.GetType("System.Byte"))
						{
							if (dc.DataType == Type.GetType("System.Int32") || dc.DataType == Type.GetType("System.Byte"))
								f.DataTextFormatString = "{0:" + strFormat + "0}";
							else if (Tools.ArrayIndexOf(this.FourDigitsColumns, dc.ColumnName) != -1)
								f.DataTextFormatString = "{0:" + strFormat + "4}";
							else if (Tools.ArrayIndexOf(this.PercentColumns, dc.ColumnName) != -1)
								f.DataTextFormatString = "{0:" + strFormat + "} %";
							else
								f.DataTextFormatString = "{0:" + strFormat + "}";
							f.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
						}
						if (dc.DataType == Type.GetType("System.DateTime"))
						{
							int z = Tools.ArrayIndexOf(this.ShortDateColumns, dc.ColumnName);
							if (z != -1)
								f.DataTextFormatString = "{0:yyyy-MM-dd}";
							else
								f.DataTextFormatString = "{0:yyyy-MM-dd HH:mm:ss}";
						}
						if ((dc.ColumnName.ToLower() == "serie card" || dc.ColumnName.ToLower() == "nr masina" || dc.ColumnName.ToLower() == "numar factura") && this.Mode == "XLS")
							f.DataTextFormatString = "=\"{0}\"";
						if ((dc.ColumnName == "SerieCard" || dc.ColumnName == "NrMasina" || dc.ColumnName == "Numar") && this.Mode == "XLS")
							f.DataTextFormatString = "=\"{0}\"";
						if ((dc.ColumnName == "VersiuneSS" || dc.ColumnName == "VersiunePOS" || dc.ColumnName == "VerPetroSmart_Server" || dc.ColumnName == "VerPetroSmart_POS") && this.Mode == "XLS")
							f.DataTextFormatString = "=\"{0}\"";

						int y = Tools.ArrayIndexOf(this.ColumnFormatNames, dc.ColumnName);
						if (y != -1)
							f.DataTextFormatString = Tools.GetHeaderText(this.ColumnFormat[y]);

						f.ItemStyle.Wrap = false;
						f.ControlStyle.CssClass = "aLink";
						columns.Add(f);
					}
					else
					{
						int t = Tools.ArrayIndexOfPos(this.DropDownColumns, dc.ColumnName, 0);
						if (t != -1)
						{
							DropDownField f = new DropDownField();
							f.ReadOnly = dc.ReadOnly;
							f.DataField = dc.ColumnName;

							f.ListDataSourceSessionDataSetKey = this.DropDownColumns[t][1];
							f.ListDataSourceSessionTableKey = this.DropDownColumns[t][2];
							f.ListDataValueField = this.DropDownColumns[t][3];
							f.ListDataTextField = this.DropDownColumns[t][4];

							f.HeaderText = Tools.GetHeaderText(dc.ColumnName);
							f.SortExpression = dc.ColumnName;
							columns.Add(f);
						}
						else
						{
							if (dc.DataType == Type.GetType("System.Boolean") && this.Mode != "XLS")
							{
								CheckBoxField f = new CheckBoxField();
								f.ReadOnly = dc.ReadOnly;
								f.DataField = dc.ColumnName;
								f.HeaderText = Tools.GetHeaderText(dc.ColumnName);
								f.SortExpression = dc.ColumnName;
								f.ItemStyle.Wrap = false;
								f.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
								columns.Add(f);
							}
							else
							{
								TextBoxField f = new TextBoxField();
								f.DataField = dc.ColumnName;
								f.HeaderText = Tools.GetHeaderText(dc.ColumnName);
								f.SortExpression = dc.ColumnName;
								f.ReadOnly = dc.ReadOnly;
								if (this.EnableEdit)
									f.ApplyFormatInEditMode = true;
								if (dc.DataType == Type.GetType("System.Int32") || dc.DataType == Type.GetType("System.Decimal") || dc.DataType == Type.GetType("System.Float") || dc.DataType == Type.GetType("System.Double") || dc.DataType == Type.GetType("System.Single") || dc.DataType == Type.GetType("System.Byte"))
								{
									if (this.Mode != "XLS")
									{
										if (dc.DataType == Type.GetType("System.Int32") || dc.DataType == Type.GetType("System.Byte"))
											f.DataFormatString = "{0:" + strFormat + "0}";
										else if (Tools.ArrayIndexOf(this.FourDigitsColumns, dc.ColumnName) != -1)
											f.DataFormatString = "{0:" + strFormat + "4}";
										else if (Tools.ArrayIndexOf(this.PercentColumns, dc.ColumnName) != -1)
											f.DataFormatString = "{0:" + strFormat + "} %";
										else
											f.DataFormatString = "{0:" + strFormat + "}";
									}
									f.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
								}
								if (dc.DataType == Type.GetType("System.DateTime"))
								{
									m_bHasDateTimeColumns = true;
									int z = Tools.ArrayIndexOf(this.ShortDateColumns, dc.ColumnName);
									if (z != -1)
										f.DataFormatString = "{0:yyyy-MM-dd}";
									else
										f.DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}";
								}
								if ((dc.ColumnName.ToLower() == "serie card" || dc.ColumnName.ToLower() == "nr masina" || dc.ColumnName.ToLower() == "numar factura") && this.Mode == "XLS")
									f.DataFormatString = "=\"{0}\"";
								if ((dc.ColumnName == "SerieCard" || dc.ColumnName == "NrMasina" || dc.ColumnName == "Numar") && this.Mode == "XLS")
									f.DataFormatString = "=\"{0}\"";
								if ((dc.ColumnName == "VersiuneSS" || dc.ColumnName == "VersiunePOS" || dc.ColumnName == "VerPetroSmart_Server" || dc.ColumnName == "VerPetroSmart_POS") && this.Mode == "XLS")
									f.DataFormatString = "=\"{0}\"";

								int y = Tools.ArrayIndexOf(this.ColumnFormatNames, dc.ColumnName);
								if (y != -1)
									f.DataFormatString = Tools.GetHeaderText(this.ColumnFormat[y]);

								if (!this.EnableEdit)
									f.NullDisplayText = "-";
								f.ItemStyle.Wrap = false;
								f.HtmlEncode = false;
								if (dc.ColumnName != "NrCrt")
									columns.Add(f);
								else
									columns.Insert(0, f);
							}
						}
					}
				}

				m_Fields = new DataControlField[columns.Count];
				columns.CopyTo(m_Fields, 0);
			}

			return columns;
		}

		protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
		{
			int numRows = base.CreateChildControls(dataSource, dataBinding);

			DataControlField[] fields = this.Fields;

			//no data rows created, create empty table if enabled
			if (numRows == 0)
			{
				//create table
				Table table = new Table();
				table.ID = this.ID;

				//create a new header row
				GridViewRow row = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
				this.InitializeRow(row, fields);
				table.Rows.Add(row);

				//create the empty row
				row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
				TableCell cell = new TableCell();
				cell.ColumnSpan = fields.Length;
				cell.Width = Unit.Percentage(100);
				cell.Controls.Add(new LiteralControl(Resources.GridView.NoRecordFound));
				row.Cells.Add(cell);
				table.Rows.Add(row);

				this.Controls.Add(table);
			}
			else if (this.Mode != "XLS")
			{
				// Creare controale ascunse
				LinkButton l21 = new LinkButton();
				l21.ID = "lbPageSize2";
				l21.Style.Add("display", "none");
				l21.Click += new EventHandler(OnClick_lbPageSize2);

				int q = this.InnerTable.Parent.Controls.IndexOf(this.InnerTable);
				this.InnerTable.Parent.Controls.AddAt(q + 1, l21);

				TextBox tt1 = new TextBox();
				tt1.ID = "txtPageSize2";
				tt1.Style.Add("display", "none");

				q = this.InnerTable.Parent.Controls.IndexOf(this.InnerTable);
				this.InnerTable.Parent.Controls.AddAt(q + 2, tt1);

				LinkButton l22 = new LinkButton();
				l22.ID = "lbFilter2";
				l22.Style.Add("display", "none");
				l22.Click += new EventHandler(OnClick_lbFilter2);

				q = this.InnerTable.Parent.Controls.IndexOf(this.InnerTable);
				this.InnerTable.Parent.Controls.AddAt(q + 3, l22);

				// Creare row
				GridViewRow row = base.CreateRow(this.InnerTable.Rows.Count, -1, DataControlRowType.Pager, DataControlRowState.Normal);
				this.InitializeRow(row, fields);
				this.InnerTable.Rows.Add(row);

				if (!this.AllowPaging && !this.EnableFilter && !this.EnableExport)
					row.Style.Add("display", "none");

				row.Cells[0].ColumnSpan = row.Cells.Count;
				row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
				for (int i = 1; i < row.Cells[0].ColumnSpan; ++i)
					row.Cells.RemoveAt(1);

				// Panel paginare
				Panel p1 = CreatePanelPaginare();
				row.Cells[0].Controls.Add(p1);
				m_ButtonAllPages_PageSize.Attributes["onclick"] = "$get('" + m_txtPageSize.ClientID + "').value = -1;";
				m_ResetButton_PageSize.Attributes["onclick"] = "$get('" + m_txtPageSize.ClientID + "').value = " + Math.Abs(m_nInitialPageSize) + ";";

				// Paginare
				Literal l1 = new Literal();
				l1.Text = Resources.GridView.LinesPerPage + ": ";
				row.Cells[0].Controls.Add(l1);

				LinkButton l2 = new LinkButton();
				l2.ID = "lbPageSize";
				l2.CssClass = "aLink";
				l2.Text = (this.AllowPaging ? this.PageSize.ToString() : Resources.GridView.AllLines);
				row.Cells[0].Controls.Add(l2);
				m_lbPageSize = l2;

				Literal l3 = new Literal();
				l3.Text = ". ";
				row.Cells[0].Controls.Add(l3);

				// Atlas popup paginare
				ModalPopupExtender mpe = new ModalPopupExtender();
				mpe.TargetControlID = l2.ID;
				mpe.PopupControlID = "pnPageSize";
				mpe.BackgroundCssClass = "modalBackground";
				mpe.DropShadow = true;
				mpe.OkControlID = "OkButton_PageSize";
				mpe.CancelControlID = "CancelButton_PageSize";
				mpe.OnOkScript = "$get('" + tt1.ClientID + "').value = $get('" + m_txtPageSize.ClientID + "').value; __doPostBack('" + l21.UniqueID + "', '');";
				row.Cells[0].Controls.Add(mpe);

				if (this.EnableFilter)
				{
					// Panel filtrare
					Panel p2 = CreatePanelFiltrare(fields);
					row.Cells[0].Controls.Add(p2);

					// Filtrare
					Literal l4 = new Literal();
					l4.Text = Resources.GridView.FilterCriterias + ": ";
					row.Cells[0].Controls.Add(l4);

					LinkButton l5 = new LinkButton();
					l5.ID = "lbFilter";
					l5.CssClass = "aLink";
					l5.Text = (((DataView)this.DataSource).RowFilter == "" ? Resources.GridView.NoFilter : ((DataView)this.DataSource).RowFilter);
					row.Cells[0].Controls.Add(l5);
					m_lbFilter = l5;

					Literal l6 = new Literal();
					l6.Text = ". ";
					row.Cells[0].Controls.Add(l6);

					// Atlas popup paginare
					ModalPopupExtender mpe2 = new ModalPopupExtender();
					mpe2.TargetControlID = l5.ID;
					mpe2.PopupControlID = "pnFilter";
					mpe2.BackgroundCssClass = "modalBackground";
					mpe2.DropShadow = true;
					mpe2.OkControlID = "OkButton_Filter";
					mpe2.CancelControlID = "CancelButton_Filter";
					mpe2.OnOkScript = "__doPostBack('" + l22.UniqueID + "', '');";
					row.Cells[0].Controls.Add(mpe2);
				}

				if (this.EnableExport)
				{
					// Export Excel
					Literal l7 = new Literal();
					l7.Text = Resources.GridView.ExportTo + " ";
					row.Cells[0].Controls.Add(l7);

					HyperLink l8 = new HyperLink();
					l8.CssClass = "aLink";
					l8.Target = "_blank";
					l8.Text = "Excel";
					l8.NavigateUrl = this.Page.Request.ApplicationPath + "/Tools/Export.aspx?ci=" + this.ClientID;
					row.Cells[0].Controls.Add(l8);

					Literal l9 = new Literal();
					l9.Text = ". ";
					row.Cells[0].Controls.Add(l9);
				}

				if (this.ShowEditLink)
				{
					LinkButton l10 = new LinkButton();
					l10.ID = "lbEdit";
					l10.CssClass = "aLink";
					l10.Text = this.EnableEdit ? Resources.GridView.NotEdit : Resources.GridView.Edit;
					l10.Click += new EventHandler(OnClick_lbEdit);
					row.Cells[0].Controls.Add(l10);
					m_lbEdit = l10;

					Literal l12 = new Literal();
					l12.Text = ". ";
					row.Cells[0].Controls.Add(l12);
				}

				if (this.ShowInsertLink)
				{
					LinkButton l11 = new LinkButton();
					l11.ID = "lbInsert";
					l11.CssClass = "aLink";
					l11.Text = this.EnableInsert ? Resources.GridView.NotInsert : Resources.GridView.Insert;
					l11.Click += new EventHandler(OnClick_lbInsert);
					row.Cells[0].Controls.Add(l11);
					m_lbInsert = l11;

					Literal l13 = new Literal();
					l13.Text = ". ";
					row.Cells[0].Controls.Add(l13);
				}

				if (m_bHasDateTimeColumns)
				{
					Control ctrlHidden = this.RecursiveFindControl(this.Page.Form.NamingContainer, "txtHidden");
					if (ctrlHidden == null)
					{
						TextBox txtHidden = new TextBox();
						txtHidden.ID = "txtHidden";
						txtHidden.ReadOnly = true;
						txtHidden.Width = 0;
						txtHidden.Height = 0;
						txtHidden.BorderWidth = 0;
						txtHidden.TabIndex = -1;
						txtHidden.Style.Add("padding", "0");
						txtHidden.Style.Add("position", "absolute");
						txtHidden.Style.Add("z-index", "1001");
						this.InnerTable.Parent.Controls.Add(txtHidden);
						ctrlHidden = txtHidden;
					}

					if (this.RecursiveFindControl(this.Page.Form.NamingContainer, "calPopup") == null)
					{
						CalendarExtender calPopup = new CalendarExtender();
						calPopup.ID = "calPopup";
						calPopup.BehaviorID = "popupCalBhvr";
						calPopup.TargetControlID = "txtHidden";
						calPopup.OnClientDateSelectionChanged = "UpdateClientDate";
						this.InnerTable.Parent.Controls.Add(calPopup);
					}

					string strJS = @"
						Sys.Application.add_load(function() { $find('popupCalBhvr')._ensureCalendar(); });

						function FireEvent(el, ev)
						{
							if (document.createEventObject) 
							{
								el.fireEvent(ev);
							} 
							else if (document.createEvent) 
							{
								var localE = document.createEvent('HTMLEvents');
								localE.initEvent(ev.substring(2, ev.length), true, true);
								el.dispatchEvent(localE);
							}
						}

						function ShowPopupCalendar(calPopupTarget)
						{
							HidePopupCalendar();

							$find('popupCalBhvr')._popupBehavior.set_parentElement(calPopupTarget);

							var hiddenTxtBox = $get('" + ctrlHidden.ClientID + @"');
							var format = calPopupTarget.format;
							$find('popupCalBhvr').set_format(format);

							var theDate = Date.parseLocale(calPopupTarget.value, format);
							if(isNaN(theDate))
							{
								$find('popupCalBhvr').set_selectedDate(new Date());
								hiddenTxtBox.value = '';
							}
							else
							{
								$find('popupCalBhvr').set_selectedDate(theDate);
								hiddenTxtBox.value = calPopupTarget.value;
							}

							FireEvent(hiddenTxtBox, 'onfocus');
						}

						function HidePopupCalendar()
						{
							$find('popupCalBhvr').hide();
							$get('" + ctrlHidden.ClientID + @"').blur();
						}

						function UpdateClientDate(cal)
						{
							var parentDateElement = $find('popupCalBhvr')._popupBehavior.get_parentElement();
							var hiddenTxtBox = $get('" + ctrlHidden.ClientID + @"');

							if(parentDateElement.value != hiddenTxtBox.value)
							{
								parentDateElement.value = hiddenTxtBox.value;
								FireEvent(parentDateElement, 'onchange');
							}
							HidePopupCalendar();
						}

						function hideCalendar(sender)
						{
							sender.get_element().blur();
						}
					";
					ScriptManager.RegisterStartupScript(this, typeof(Page), "DateTimeColumnsJS", strJS, true);
				}
			}

			return numRows;
		}
#endregion

#region Create custom controls
		private Panel CreatePanelPaginare()
		{
			// Panel paginare
			Panel p1 = new Panel();
			p1.ID = "pnPageSize";
			p1.CssClass = "modalPopup";
			p1.Style.Add("display", "none");

			Table t1 = new Table();
			p1.Controls.Add(t1);

			// row[0]
			TableRow tr = new TableRow();
			t1.Rows.Add(tr);

			TableCell td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.HorizontalAlign = HorizontalAlign.Center;
			td.Text = "<u>" + Resources.GridView.NrLiniiPagina + "</u>:";

			// row[1]
			tr = new TableRow();
			t1.Rows.Add(tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;

			Literal l11 = new Literal();
			l11.Text = "<br />";
			td.Controls.Add(l11);

			TextBox tb1 = new TextBox();
			tb1.ID = "txtPageSize";
			tb1.Width = Unit.Pixel(100);
			tb1.Text = (this.AllowPaging ? this.PageSize.ToString() : "-1");
			td.Controls.Add(tb1);
			m_txtPageSize = tb1;

			HtmlInputButton inp1 = new HtmlInputButton();
			inp1.ID = "ButtonAllPages_PageSize";
			inp1.Value = Resources.GridView.AllLines;
			inp1.Attributes["AccessKey"] = "a";
			td.Controls.Add(inp1);
			m_ButtonAllPages_PageSize = inp1;

			// row[2]
			tr = new TableRow();
			t1.Rows.Add(tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.HorizontalAlign = HorizontalAlign.Center;

			Literal l12 = new Literal();
			l12.Text = "<br />";
			td.Controls.Add(l12);

			Button b1 = new Button();
			b1.ID = "OkButton_PageSize";
			b1.Text = "OK";
			b1.AccessKey = "f";
			td.Controls.Add(b1);

			Button b2 = new Button();
			b2.ID = "CancelButton_PageSize";
			b2.Text = Resources.GridView.Cancel;
			b2.AccessKey = "c";
			td.Controls.Add(b2);

			HtmlInputButton inp2 = new HtmlInputButton();
			inp2.ID = "ResetButton_PageSize";
			inp2.Value = Resources.GridView.Reset;
			inp2.Attributes["AccessKey"] = "r";
			td.Controls.Add(inp2);
			m_ResetButton_PageSize = inp2;

			return p1;
		}

		private Panel CreatePanelFiltrare(DataControlField[] fields)
		{
			// Panel filtrare
			Panel p1 = new Panel();
			p1.ID = "pnFilter";
			p1.CssClass = "modalPopup";
			p1.Style.Add("display", "none");

			Table t1 = new Table();
			p1.Controls.Add(t1);

			// row[0]
			TableRow tr = new TableRow();
			t1.Rows.Add(tr);

			TableCell td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.ColumnSpan = 2;
			td.HorizontalAlign = HorizontalAlign.Center;
			td.Text = "<u>" + Resources.GridView.FilterCriteria + "</u>:";

			// row[1]
			tr = new TableRow();
			t1.Rows.Add(tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;

			Table t2 = new Table();
			t2.ID = "tblFilter";
			td.Controls.Add(t2);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;

			Table t3 = new Table();
			t3.ID = "tblFilter2";
			td.Controls.Add(t3);

			// row[2]
			tr = new TableRow();
			t1.Rows.Add(tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.ColumnSpan = 2;

			Table t4 = new Table();
			td.Controls.Add(t4);
			t4.Width = Unit.Percentage(100);

			tr = new TableRow();
			if (!this.EnableOtherCriterias)
				tr.Style.Add("display", "none");
			t4.Rows.Add(tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.Text = Resources.GridView.OtherCriterias + ":";

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.Width = Unit.Percentage(100);

			TextBox tb1 = new TextBox();
			tb1.ID = "txtAlteCriterii";
			tb1.Width = Unit.Percentage(95);
			if (this.HtFilter[tb1.ID] != null)
				tb1.Text = this.HtFilter[tb1.ID].ToString();
			td.Controls.Add(tb1);

			// row[3]
			tr = new TableRow();
			t1.Rows.Add(tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.ColumnSpan = 2;

			Label l1 = new Label();
			l1.ID = "lblExplicatieData";
			l1.Text = Resources.GridView.DataFormatDescription;
			td.Controls.Add(l1);

			// row[4]
			tr = new TableRow();
			t1.Rows.Add(tr);

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.HorizontalAlign = HorizontalAlign.Center;

			Button b1 = new Button();
			b1.ID = "OkButton_Filter";
			b1.Text = "OK";
			b1.AccessKey = "f";
			td.Controls.Add(b1);

			Button b2 = new Button();
			b2.ID = "CancelButton_Filter";
			b2.Text = Resources.GridView.Cancel;
			b2.AccessKey = "c";
			td.Controls.Add(b2);

			HtmlInputButton inp2 = new HtmlInputButton();
			inp2.ID = "ResetButton_Filter";
			inp2.Value = Resources.GridView.Reset;
			inp2.Attributes["AccessKey"] = "r";
			inp2.Attributes["onclick"] = "OnClick_ResetButton_Filter('" + this.ClientID + "');";
			td.Controls.Add(inp2);

			BuildFilterTable(t2, t3, l1, fields);

			return p1;
		}

		private object[] GetFilterArray(DataControlField[] fields)
		{
			object[] o = new object[fields.Length];
			int i = 0;
			DataTable dt = ((DataView)this.DataSource).Table;
			foreach (DataControlField dcfc in fields)
			{
				string strCaption = "";
				int nOrdinal = -1;
				Type tDataType = null;
				if (dcfc is CheckBoxField)
				{
					strCaption = ((CheckBoxField)dcfc).HeaderText;
					nOrdinal = dt.Columns[((CheckBoxField)dcfc).DataField].Ordinal;
					tDataType = dt.Columns[((CheckBoxField)dcfc).DataField].DataType;
				}
				else if (dcfc is HyperLinkField)
				{
					strCaption = ((HyperLinkField)dcfc).HeaderText;
					nOrdinal = dt.Columns[((HyperLinkField)dcfc).DataTextField].Ordinal;
					tDataType = dt.Columns[((HyperLinkField)dcfc).DataTextField].DataType;
				}
				else if (dcfc is TextBoxField)
				{
					strCaption = ((TextBoxField)dcfc).HeaderText;
					nOrdinal = dt.Columns[((TextBoxField)dcfc).DataField].Ordinal;
					tDataType = dt.Columns[((TextBoxField)dcfc).DataField].DataType;
				}
				else if (dcfc is DropDownField)
				{
					strCaption = ((DropDownField)dcfc).HeaderText;
					nOrdinal = dt.Columns[((DropDownField)dcfc).DataField].Ordinal;
					tDataType = dt.Columns[((DropDownField)dcfc).DataField].DataType;
				}
				else if (dcfc is BoundField)
				{
					strCaption = ((BoundField)dcfc).HeaderText;
					nOrdinal = dt.Columns[((BoundField)dcfc).DataField].Ordinal;
					tDataType = dt.Columns[((BoundField)dcfc).DataField].DataType;
				}
				o[i] = new object[3];
				((object[])o[i])[0] = strCaption;
				((object[])o[i])[1] = nOrdinal;
				((object[])o[i])[2] = tDataType;
				++i;
			}
			return o;
		}

		private void BuildFilterTable(Table tblFilter, Table tblFilter2, Label lblExplicatieData, DataControlField[] fields)
		{
			int i = 0;
			bool bDate = false;
			tblFilter.Rows.Clear();
			tblFilter2.Rows.Clear();
			object[] oo = GetFilterArray(fields);
			Hashtable htFilter = this.HtFilter;
			int n = oo.Length;
			foreach (object[] o in oo)
			{
				string strCaption = (string)o[0];
				int nOrdinal = (int)o[1];
				Type tDataType = (Type)o[2];

				TableRow tr = new TableRow();

				TableHeaderCell th = new TableHeaderCell();
				th.HorizontalAlign = HorizontalAlign.Left;
				th.Wrap = false;
				Literal lName = new Literal();
				lName.Text = strCaption;
				th.Controls.Add(lName);
				tr.Cells.Add(th);

				TableCell td = new TableCell();
				td.Wrap = false;
				Literal lOp = new Literal();
				lOp.Text = Resources.GridView.equal;
				td.Controls.Add(lOp);
				tr.Cells.Add(td);

				td = new TableCell();
				td.Wrap = false;
				TextBox t = new TextBox();
				t.ID = "txtFilter_from_" + nOrdinal.ToString();
				t.Width = 50;
				if (htFilter[t.ID] != null)
					t.Text = htFilter[t.ID].ToString();
				td.Controls.Add(t);
				tr.Cells.Add(td);

				if (tDataType == System.Type.GetType("System.DateTime") || tDataType == System.Type.GetType("System.Decimal") || tDataType == System.Type.GetType("System.Int32"))
				{
					tr.Cells[1].Text = Resources.GridView.From;

					td = new TableCell();
					td.Wrap = false;
					Literal lOp2 = new Literal();
					lOp2.Text = Resources.GridView.To;
					td.Controls.Add(lOp2);
					tr.Cells.Add(td);

					td = new TableCell();
					td.Wrap = false;
					TextBox t2 = new TextBox();
					t2.ID = "txtFilter_to_" + nOrdinal.ToString();
					t2.Width = 50;
					if (htFilter[t2.ID] != null)
						t2.Text = htFilter[t2.ID].ToString();
					td.Controls.Add(t2);
					tr.Cells.Add(td);
				}
				else
				{
					td.ColumnSpan = 3;
					t.Width = Unit.Percentage(96);
				}

				if (n > 25 && i > n / 2)
					tblFilter2.Rows.Add(tr);
				else
					tblFilter.Rows.Add(tr);
				++i;
				if (tDataType == System.Type.GetType("System.DateTime"))
					bDate = true;
			}
			lblExplicatieData.Text = (bDate ? Resources.GridView.DataFormatDescription : "<BR />");
		}

		private string GetFilter(Control cParent)
		{
			string strFilter = "";
			ArrayList arFilter = new ArrayList();
			Hashtable htFilter = new Hashtable();
			DataTable dt = ((DataView)this.DataSource).Table;
			foreach (DataColumn dc in dt.Columns)
			{
				Control cFrom = cParent.FindControl("txtFilter_from_" + dc.Ordinal.ToString());
				Control cTo = cParent.FindControl("txtFilter_to_" + dc.Ordinal.ToString());
				if (cFrom != null)
				{
					if (cTo == null)
					{
						if (((TextBox)cFrom).Text != "")
						{
							arFilter.Add("([" + dc.ColumnName + "] LIKE '%" + ((TextBox)cFrom).Text + "%')");
							htFilter.Add(((TextBox)cFrom).ID, ((TextBox)cFrom).Text);
						}
					}
					else
					{
						if (dc.DataType == System.Type.GetType("System.DateTime"))
						{
							if (((TextBox)cFrom).Text != "")
							{
								arFilter.Add("([" + dc.ColumnName + "] >= '" + ((TextBox)cFrom).Text + "')");
								htFilter.Add(((TextBox)cFrom).ID, ((TextBox)cFrom).Text);
							}
							if (((TextBox)cTo).Text != "")
							{
								arFilter.Add("([" + dc.ColumnName + "] <= '" + ((TextBox)cTo).Text + "')");
								htFilter.Add(((TextBox)cTo).ID, ((TextBox)cTo).Text);
							}
						}
						else
						{
							if (((TextBox)cFrom).Text != "")
							{
								arFilter.Add("([" + dc.ColumnName + "] >= " + ((TextBox)cFrom).Text + ")");
								htFilter.Add(((TextBox)cFrom).ID, ((TextBox)cFrom).Text);
							}
							if (((TextBox)cTo).Text != "")
							{
								arFilter.Add("([" + dc.ColumnName + "] <= " + ((TextBox)cTo).Text + ")");
								htFilter.Add(((TextBox)cTo).ID, ((TextBox)cTo).Text);
							}
						}
					}
				}
			}
			TextBox txtAlteCriterii = (TextBox)cParent.FindControl("txtAlteCriterii");
			if (txtAlteCriterii.Text != "")
			{
				arFilter.Add("(" + txtAlteCriterii.Text + ")");
				htFilter.Add(((TextBox)txtAlteCriterii).ID, ((TextBox)txtAlteCriterii).Text);
			}
			this.HtFilter = htFilter;
			string[] ss = new string[arFilter.Count];
			arFilter.CopyTo(ss);
			strFilter = string.Join(" AND ", ss);
			return strFilter;
		}
#endregion

#region Others
		public void AddLinkedStyleSheet(Page page, string stylesheet)
		{
			bool bAdded = false;
			foreach (Control c in page.Header.Controls)
				if (c is HtmlLink && ((HtmlLink)c).Href == stylesheet)
				{
					bAdded = true;
					continue;
				}
			if (!bAdded)
			{
				HtmlLink link = new HtmlLink();
				link.Href = stylesheet;
				link.Attributes["rel"] = "stylesheet";
				link.Attributes["type"] = "text/css";

				page.Header.Controls.Add(link);
			}
		}
#endregion

	}
}
